package com.dublbo.addressbook.frame.person;

import com.dublbo.addressbook.frame.CPersonMainPanel;
import com.dublbo.jpSwing.JpButton;
import com.dublbo.jpSwing.layout.JpColumnLayout;
import com.dublbo.jpSwing.popup.JpPopupPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class ImportOrExportPopupPanel extends JpPopupPanel implements ActionListener {
    private CPersonMainPanel ui;
    private JpButton button1 = new JpButton("从文件中导入通讯录");
    private JpButton button2 = new JpButton("导出通讯录");
    private int width;

    public ImportOrExportPopupPanel(CPersonMainPanel ui ){
        this.ui = ui;
        this.width = 150;

        this.setBorder(BorderFactory.createLineBorder(new Color(0x9AC0CD)));
        this.setPreferredSize(new Dimension(this.width,100));
        this.setLayout(new JpColumnLayout(2));
        this.setBackground(new Color(0xF8F8FF));

        initCenter();
    }

    private void initCenter(){
        this.add(button1);
        this.add(button2);

        button1.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button2.setCursor(new Cursor(Cursor.HAND_CURSOR));

        button1.addActionListener(this);
        button2.addActionListener(this);
    }

    @Override
    public void showPopup(Component owner, int x, int y) {
        super.showPopup(owner, x-this.width, y);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String btnTitle = ((JpButton) e.getSource()).getText();
        if(btnTitle.equals("导出通讯录")){

            JFileChooser jfc = new JFileChooser();
            jfc.setSelectedFile(new File("address.csv"));
            jfc.setDialogTitle("保存 csv 文件");
            int val = jfc.showSaveDialog(null);
            if(val == JFileChooser.APPROVE_OPTION){ // 点 “保存” 按钮
                System.out.println(jfc.getSelectedFile().getPath());
                CPersonExportTask task = new CPersonExportTask(this.ui);
                task.execute(jfc.getSelectedFile().getPath());
            }
        }

    }
}
